package com.novel.service.impl;

import cn.hutool.json.JSONUtil;
import com.novel.dto.Result;
import com.novel.entity.ShopType;
import com.novel.mapper.ShopTypeMapper;
import com.novel.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

import static com.novel.utils.RedisConstants.CACHE_SHOPTYPE_KEY;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result queryList() {
        //从redis查询
        String key = CACHE_SHOPTYPE_KEY;
        List<String> shopType = stringRedisTemplate.opsForList().range(key, 0, -1);
        Long count = stringRedisTemplate.opsForList().size(key);
        //存在，直接返回
        List<ShopType> list = new ArrayList<>();
        if(count == 10){
            for (String s:shopType) {
                ShopType bean = JSONUtil.toBean(s, ShopType.class);
                list.add(0,bean);
            }
            return Result.ok(list);
        }
        //不存在，查询mysql数据库
        List<ShopType> shoptype = query().orderByAsc("sort").list();
        //不存在，返回错误信息
        if(shopType == null){
            return Result.fail("信息不存在");
        }
        //存在，把数据写入redis
        for (ShopType a:shoptype) {
            String str = JSONUtil.toJsonStr(a);
            stringRedisTemplate.opsForList().leftPush(key,str);
        }
        //返回
        return Result.ok(shoptype);
    }
}
